
#include <iostream>
#include "ipc.h"
using namespace std;

#include <cerrno>

int main()
{
    // 生成key值
    key_t key = ftok(IPC_PATH_NAME, IPC_PROJ_ID);
    if (key == -1)
    {
        ERR_EXIT("ftok");
    }
    else
        cout << "ftok success" << endl;

    // 创建共享内存
    int shm_id = shmget(key, 4096, IPC_CREAT | IPC_EXCL | 0666);
    if (shm_id == -1)
    {
        ERR_EXIT("shmget");
    }
    else
        cout << "ftok success" << endl;

    // shmat -> 将进程与共享内存建立连接
    void* virshmaddr = shmat(shm_id,NULL,0);
    if((long long)virshmaddr == -1)
    {
        ERR_EXIT("shmat");
    }
    else printf("共享内存映射地址:%p\n",virshmaddr);

    // shmdt -> 将进程与共享内存移除连接
    int ret = shmdt(virshmaddr);
    if(ret == -1)
    {
        ERR_EXIT("shmdt");
    }
    else cout << "shmdt success" << endl;

    // 获取共享内存数据结构信息
    shmid_ds ds = {0};
    int ret1 = shmctl(shm_id, IPC_STAT, &ds);
    if (ret1 == -1)
    {
        ERR_EXIT("shmctl IPC_STAT");
    }
    else
    {
         // ... 打印共享内存数据结构相关信息
    }
    // 设置共享内存数据结构信息
    int ret2 = shmctl(shm_id, IPC_SET, &ds);
    if (ret2 == -1)
    {
        ERR_EXIT("shmctl IPC_SET");
    }

    // 删除共享内存
    int ret3 = shmctl(shm_id,IPC_RMID,NULL);
    if(ret3 == -1)
    {
        ERR_EXIT("shmctl IPC_RMID");
    }
    else cout << "shmctl success" << endl;

    return 0;
}
